<template>
    <div class="content">
        <div class="detail_mian" v-for="(item,index) in this.batchBillList" :key="item.index">
            <el-row class="title_block enterprise_info hpx-title-border">
                <span class="title_text">票据信息</span>
                <span class="col"><i class="iconfont icon-jine"></i> 票面金额：<span class="hpx-red-tips">{{item.faceAmount ? item.faceAmount + '万元' : '--'}}</span></span>
                <span class="col"><i class="iconfont icon-xuanzerili"></i> 到期日：<span class="hpx-red-tips">{{formatDate(item.dueDate)}}</span></span>
                <span class="top_btn">
                    <el-button type="danger" plain size="mini" v-if="billQuantity != 1" @click="deleteTemplate(index)">
                        <i class="iconfont icon-shanchu"></i> 删除
                        </el-button>
                    <el-button type="primary" plain size="small" @click="pickUpDetail(item)">
                        {{item.bill_detail ? '收起' : '展开'}} <i :class="[item.bill_detail ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                    </el-button>
                </span>
            </el-row>
            <div class="mian_block" v-if="item.bill_detail">
                <el-form class="form-box" label-width="125px" :model="item" ref="form" :rules="rules" size="small">
                    <el-row class="posted-form-con">
                        <el-row class="posted-title-img">
                            <el-form-item label="上传票据图片：" prop="bill_img"></el-form-item>
                            <div class="posted-img-box">
                                <div class="upload-img-box">
                                    <div class="img-box">
                                        <i class="iconfont icon-shangchuanshanchu delete-bill-btn" @click="removeFort(index)"></i>
                                        <!--<img :src="item.billFrontPhoto" alt="">-->
                                        <ImageZoom
                                                :width='290'
                                                :height='210'
                                                :image="item.billFrontPhoto"
                                        ></ImageZoom>
                                    </div>
                                    <div class="upload-btn" @click="listInx(index)">
                                        <UploaderImages @input="forntBillImg" uploadText="上传票据正面"></UploaderImages>
                                    </div>
                                </div>
                                <div class="upload-img-box">
                                    <div class="img-box">
                                        <i class="iconfont icon-shangchuanshanchu delete-bill-btn" @click="removeBack1(index)"></i>
                                        <!--<img :src="item.billBackPhoto1" alt="">-->
                                        <ImageZoom
                                                :width='290'
                                                :height='210'
                                                :image="item.billBackPhoto1"
                                        ></ImageZoom>
                                    </div>
                                    <div class="upload-btn" @click="listInx(index)">
                                        <UploaderImages @input="backBillImg1" uploadText="上传背书面1"></UploaderImages>
                                    </div>
                                </div>
                                <div class="upload-img-box">
                                    <div class="img-box">
                                        <i class="iconfont icon-shangchuanshanchu delete-bill-btn" @click="removeBack2(index)"></i>
                                        <!--<img :src="item.billBackPhoto2" alt="">-->
                                        <ImageZoom
                                                :width='290'
                                                :height='210'
                                                :image="item.billBackPhoto2"
                                        ></ImageZoom>
                                    </div>
                                    <div class="upload-btn" @click="listInx(index)">
                                        <UploaderImages @input="backBillImg2" uploadText="上传背书面2"></UploaderImages>
                                    </div>
                                </div>
                            </div>
                        </el-row>
                        <el-row v-if="item.isShowNumber">
                            <el-col :span="9">
                                <el-form-item label="票据号：" class="billNumber">
                                    <el-input type="number" oninput="if(value.length>30)value=value.slice(0,30)" v-model="item.billNumber" placeholder="请输入票据号"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="9">
                                <el-form-item label="承兑行：" class="accept_bank" prop="acceptor">
                                    <el-input v-model="item.acceptor" @input="inputAccept(item)" placeholder="请输入承兑行"></el-input>
                                    <Select :data="bankList" @select-item="selectItem" v-if="item.isShowBank"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="9" class="bill_price">
                                <el-form-item label="票面金额：" prop="faceAmount">
                                    <el-input type="number" v-model="item.faceAmount" @input="inputAmount(index)" placeholder="请输入不大于500万"></el-input>
                                    <span class="company">万元</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="9">
                                <el-form-item label="到期日：" prop="dueDate" class="picker_date">
                                    <el-date-picker
                                        v-model="item.dueDate"
                                        type="date"
                                        placeholder="选择日期"
                                        format="yyyy-MM-dd"
                                        :picker-options="pickerOptions">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="9">
                                <el-form-item label="贴现日：" prop="applyDate" class="picker_date discount_date">
                                    <el-date-picker
                                        v-model="item.applyDate"
                                        type="date"
                                        placeholder="选择日期"
                                        format="yyyy-MM-dd">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-button type="info" size="small" @click="clear(item)">清空</el-button>
                                <el-button type="primary" size="small" @click="searchRate(item)">查询</el-button>
                            </el-col>
                        </el-row>
                        <el-row class="searchResult" v-if="item.isShowRate">
                            <el-col :span="4">银行报价</el-col>
                            <el-col :span="6">利率(%)：<span class="hpx-red-tips">{{item.billRate}}</span></el-col>
                            <el-col :span="6">每十万扣(元)：<span class="hpx-red-tips">{{item.everyOneHunderdThousandPlus}}</span></el-col>
                            <el-col :span="8">成交金额(万元)：<span class="hpx-red-tips">{{item.transactionAmount}}</span></el-col>
                        </el-row>
                    </el-row>
                </el-form>
            </div>
        </div>
        <el-row class="add_bill">
            <el-row class="center">
                <span class="title"><i class="iconfont icon-jine"></i> 票面总金额(万元)：<span class="hpx-red-tips">{{totalPrice != 0 ? totalPrice : '--'}}</span></span>
                <span class="title"><i class="iconfont icon-xuanzerili"></i> 票面总张数(张)：<span class="hpx-red-tips">{{billFaceNum}}</span></span>
                <el-button size="mini" class="add_btn" @click="addTemplate()" v-if="isaddable"><i class="iconfont icon-tianjia"></i> 继续添加</el-button>
            </el-row>
        </el-row>
        <el-row class="pubish">
            <el-button type="primary" size="small" @click="initiate()">发起速贴申请</el-button>
        </el-row>
        <el-row class="hr"></el-row>
        <el-row class="publish_tips">
            <div class="secondary_title"><i class="iconfont icon-tixing hpx-red-tips"></i>提醒：</div>
            <div class="secondary_content">
                贴现企业收款账户必须为提票账户；单张贴现票面金额不得超过500万元；贴现票据的承兑行必须在直贴行授信范围内；贴现申请利率必须与平台公示快贴利率一致；
                <span class="hpx-red-tips">
                    直贴银行目前不接受回头等瑕疵电票；贴现企业提票网银: 建议不要通过建行和农行网银提票至快贴银行(可能会导致无法提票或回款较慢等)；银行速贴业务办理时间：
                    工作日09:00-17:00。
                </span>
            </div>
        </el-row>
    </div>
</template>

<script lang="ts">
    import {Vue, Component, Watch} from 'vue-property-decorator'
    import moment from 'moment'
    import _ from 'lodash'
    import Select from '@component/common/Select.vue'
    import UploaderImages from '@component/common/UploaderImages.vue'
    import ImageZoom from '@component/common/ImageZoom.vue';
    @Component({
        components:{
            Select,
            UploaderImages,
            ImageZoom
        }
    })
    export default class Publish extends Vue {
    //data
        isaddable = true
        batchBillList:any = []
        listIten:number = 0
        batchBill = {
            billFrontPhoto: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-front.png',
            billBackPhoto1: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-brank.png',
            billBackPhoto2: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-brank.png',
            billFrontPhotoId: '',
            billFrontPhotoId1: '',
            billFrontPhotoId2: '',
            billNumber: '',
            // billPrice: '',
            acceptor: '',
            uBankNo: '',
            faceAmount: '',
            dueDate: '',
            applyDate: new Date(),
            billRate: '',     //利率
            everyOneHunderdThousandPlus: '',//每十万扣
            transactionAmount: '',    //成交金额
            bill_detail: true,
            isShowBank: false,
            isShowRate: false,
            isShowNumber: false
        }
        rules = {
            bill_img: [
                {required: true, trigger: 'blur'}
            ],
            acceptor: [
                {required: true, message: '请输入承兑行', trigger: 'blur'}
            ],
            faceAmount: [
                {required: true, message: '请输入票面金额', trigger: 'blur'}
            ],
            dueDate: [
                {required: true, message: '请选择到期日', trigger: 'blur'}
            ],
            applyDate: [
                {required: true, message: '请选择贴现日', trigger: 'blur'}
            ]
        }
        bankList:any = []
        model:any = {}
        totalPrice:number = 0
        billFaceNum:number = 0
    //methods
        //查询单个详情
        async searchSingleDetail () {
            if(!this.$route.params.id){
                return false
            }
            this.isaddable = false
            let res = await this.$http.get(`fbank/trade/getBill/${this.$route.params.id}`)
            if(res.status == 200){
                this.batchBillList[0].billFrontPhoto = res.data.billFrontPhoto ? res.data.billFrontPhoto : this.batchBill.billFrontPhoto
                this.batchBillList[0].billBackPhoto1 = res.data.billBackPhoto1 ? res.data.billBackPhoto1 : this.batchBill.billBackPhoto1
                this.batchBillList[0].billBackPhoto2 = res.data.billBackPhoto2 ? res.data.billBackPhoto2 : this.batchBill.billBackPhoto2
                this.batchBillList[0].billFrontPhotoId = res.data.billFrontPhoto ? '0' : ''
                this.batchBillList[0].billFrontPhotoId1 = res.data.billBackPhoto1 ? '1' : ''
                this.batchBillList[0].billFrontPhotoId2 = res.data.billBackPhoto2 ? '2' : ''
                this.batchBillList[0].faceAmount = res.data.billPriceOrigin*10000/100000000
                this.batchBillList[0].dueDate = res.data.dueDate
                this.batchBillList[0].id = res.data.id
                this.totalPrice = res.data.billPriceOrigin*10000/100000000
                this.billFaceNum = 1

                // let params = {
                //     bankName: res.data.acceptor
                // }
                // let res1:any = this.$http.get('fbank/constants/bankCode',{params})
            }
        }
        //展开收缩
        pickUpDetail (item) {
            item.bill_detail = !item.bill_detail;
        }
        //填充模板
        async fillingTemplate () {
            let template = _.cloneDeep(this.batchBill)
            this.batchBillList.push(template)
        }
        //添加模板
        addTemplate () {
            this.fillingTemplate()
        }
        //删除模板
        deleteTemplate (index:number) {
            this.batchBillList.splice(index,1)
            this.totalPrice = 0;
            this.billFaceNum = 0
            for (var i = 0; i < this.batchBillList.length; i++) {
                this.totalPrice += this.batchBillList[i].faceAmount*1;
                if (this.batchBillList[i].billFrontPhotoId != '') {
                    this.billFaceNum += 1
                }
            }
        }
        //正在上传图片的下标
        listInx (inx: number) {
            this.listIten = inx;
        }
        // 票据正面ocr
        async billOcr (imageUrl: string) {
            let res = await this.$http.get(`ocr/bill?adderss=${imageUrl}`)
            this.batchBillList[this.listIten].billNumber = res.data.bill_number;
            this.batchBillList[this.listIten].billPrice = res.data.bill_sum_price;
        }
        //上传正面
        forntBillImg (valData: any) {
            this.billFaceNum = 0
            if(valData){
                this.batchBillList[this.listIten].billFrontPhoto = valData.path;
                this.batchBillList[this.listIten].billFrontPhotoId = valData.id;
                //this.billOcr(this.batchBillList[this.listIten].billFrontPhoto);
                for (var i = 0; i < this.batchBillList.length; i++) {
                    if (this.batchBillList[i].billFrontPhotoId != '') {
                        this.billFaceNum += 1
                    }
                }
            }
        }
        // 上传背面1
        backBillImg1 (valData: any) {
            if(valData){
                this.batchBillList[this.listIten].billBackPhoto1 = valData.path;
                this.batchBillList[this.listIten].billFrontPhotoId1 = valData.id;
            }
        }
        // 上传背面2
        backBillImg2 (valData: any) {
            if(valData){
                this.batchBillList[this.listIten].billBackPhoto2 = valData.path;
                this.batchBillList[this.listIten].billFrontPhotoId2 = valData.id;
            }
        }
        // 删除正面
        removeFort (index) {
            this.billFaceNum = 0
            this.batchBillList[index].billFrontPhoto = 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-front.png';
            this.batchBillList[index].billFrontPhotoId = '';
            for (var i = 0; i < this.batchBillList.length; i++) {
                if (this.batchBillList[i].billFrontPhotoId != '') {
                    this.billFaceNum += 1
                }
            }
        }
        //删除背面1
        removeBack1 (index) {
            this.batchBillList[index].billBackPhoto1 = 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-brank.png';
        }
        //删除背面2
        removeBack2 (index) {
            this.batchBillList[index].billBackPhoto2 = 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-brank.png';
        }
        
        //输入银行
        inputAccept (item) {
            this.model = item
            if(item.acceptor){
                this.getBankCode(item)
            }else{
                item.isShowBank = false
            }
        }
        //富民银行查询
        async getBankCode (item) {
            let params = {
                bankName: item.acceptor
            }
            let res:any = await this.$http.get('fbank/constants/bankCode',{params})
            if(res.status == 200){
                if(res.data){
                    if(res.data.length == 1){
                        item.uBankNo = res.data[0].bankCode
                    }
                    this.bankList = [...res.data]
                    item.isShowBank = true
                }
                // else{
                //     //未找到相关银行
                //     this.$alert(res.msg,'提示',{
                //         confirmButtonText: '确定',
                //         customClass: 'custom-message-box'
                //     })
                // }
            }
        }
        //选择银行
        selectItem (item) {
            this.model.isShowBank = false
            this.model.acceptor = item.bankName
            this.model.uBankNo = item.bankCode
        }
        //查询报价
        async searchRate (item) {
            // this.$refs[item].validate((valid) => {
            //     if (valid) {
            //         alert('submit!');
            //     } else {
            //         console.log('error submit!!');
            //         return false;
            //     }
            // });
            let params = {
                uBankNo: item.uBankNo,
                faceAmount: item.faceAmount*10000,
                applyDate: moment(item.applyDate).format('YYYY/MM/DD'),
                dueDate: moment(item.dueDate).format('YYYY/MM/DD')
            }
            let res = await this.$http.get('fbank/rate/one',{params})
            if(res.status == 200){
                item.billRate = res.data.sData.billRate,
                item.everyOneHunderdThousandPlus = res.data.sData.everyInterest,
                item.transactionAmount = Number(res.data.sData.realMoney)*10000/100000000,
                console.log(Number(res.data.sData.realMoney))
                item.isShowRate = true
            }
            // else{
            //     this.$alert(res.msg,'提示',{
            //         confirmButtonText: '确定',
            //         customClass: 'custom-message-box'
            //     })
            // }
        }
        //清空条件
        clear (item) {
            item.acceptor = ''
            item.uBankNo = ''
            item.faceAmount = ''
            item.dueDate = ''
            item.applyDate = new Date()
            item.isShowBank = false
            item.isShowRate = false
        }
        //限制日期选择的最小值
        pickerOptions = {
            disabledDate(time) {
                return time.getTime() < Date.now() 
            }
        }
        //格式化到期日
        formatDate (dateStr:string) {
            if(!dateStr) return ''
            return moment(dateStr).format('YYYY-MM-DD')
        }
        //计算总金额
        inputAmount (index:number) {
            this.totalPrice = 0;
            for (var i = 0; i < this.batchBillList.length; i++) {
                this.totalPrice += this.batchBillList[i].faceAmount*1;
            }
        }
        //票据数量
        get billQuantity () {
            return this.batchBillList.length
        }
        //发起速贴
        async initiate () {
            let listFBankBillTrade = _.cloneDeep(this.batchBillList)
            for(var i = 0; i < listFBankBillTrade.length; i++){
                if(!listFBankBillTrade[i].billFrontPhotoId){
                    this.$alert('您有票据正面图片未上传','提示',{
                        confirmButtonText: '确定',
                        customClass: 'custom-message-box'
                    })
                    return false
                }
                if(!listFBankBillTrade[i].billFrontPhotoId1 && !listFBankBillTrade[i].billFrontPhotoId2){
                    this.$alert('每个报价必须至少上传一张背书面图片','提示',{
                        confirmButtonText: '确定',
                        customClass: 'custom-message-box'
                    })
                    return false
                }
                if(!listFBankBillTrade[i].isShowRate){
                    this.$alert('请先查询利率','提示',{
                        confirmButtonText: '确定',
                        customClass: 'custom-message-box'
                    })
                    return false
                }
                if(!listFBankBillTrade[i].billFrontPhotoId1){
                    listFBankBillTrade[i].billBackPhoto1 = ''
                }
                if(!listFBankBillTrade[i].billFrontPhotoId2){
                    listFBankBillTrade[i].billBackPhoto2 = ''
                }
                listFBankBillTrade[i].discountedDate = moment(listFBankBillTrade[i].applyDate).format('YYYY-MM-DD')
                listFBankBillTrade[i].dueDate = moment(listFBankBillTrade[i].dueDate).format('YYYY-MM-DD')
                listFBankBillTrade[i].billPrice = listFBankBillTrade[i].faceAmount*10000
                listFBankBillTrade[i].transactionAmount = listFBankBillTrade[i].transactionAmount*10000
                delete listFBankBillTrade[i].billFrontPhotoId
                delete listFBankBillTrade[i].billFrontPhotoId1
                delete listFBankBillTrade[i].billFrontPhotoId2
                delete listFBankBillTrade[i].faceAmount
                delete listFBankBillTrade[i].applyDate
                delete listFBankBillTrade[i].bill_detail
                delete listFBankBillTrade[i].isShowBank
                delete listFBankBillTrade[i].isShowRate
            }
            let form = this.$route.params.id ? {...listFBankBillTrade[0]} : {listFBankBillTrade: listFBankBillTrade}
            let url = this.$route.params.id ? 'fbank/trade/pushBillAgain' : 'fbank/trade/pushBill'
            let res = await this.$http.post(url,form)
            if(res.status == 200){
                this.$router.push('/discount/order')
            }else if(res.status == 505){
                let failIndex = res.data.failIndexs
                failIndex.forEach(element => {
                    this.batchBillList[element].isShowNumber = true
                })
                // this.$alert(res.msg,'提示',{
                //     confirmButtonText: '确定',
                //     customClass: 'custom-message-box',
                //     callback: action => {
                //     }
                // })
            }
        }
        @Watch('$route')
        ca(route) {
            if (route.params.id == undefined) {
                this.batchBillList = [{
                    billFrontPhoto: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-front.png',
                    billBackPhoto1: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-brank.png',
                    billBackPhoto2: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/billImgTem/bill-brank.png',
                    billFrontPhotoId: '',
                    billFrontPhotoId1: '',
                    billFrontPhotoId2: '',
                    billNumber: '',
                    // billPrice: '',
                    acceptor: '',
                    uBankNo: '',
                    faceAmount: '',
                    dueDate: '',
                    applyDate: new Date(),
                    billRate: '',     //利率
                    everyOneHunderdThousandPlus: '',//每十万扣
                    transactionAmount: '',    //成交金额
                    bill_detail: true,
                    isShowBank: false,
                    isShowRate: false,
                    isShowNumber: false
                }]
                this.totalPrice = 0;
                this.billFaceNum = 0
            }
            if (route.params.id != undefined) {
                this.searchSingleDetail()
            }
        }
        mounted () {
            this.fillingTemplate()
            if (this.$route.params.id != undefined) {
                this.searchSingleDetail()
            }
        }
    }
</script>

<style lang="scss" scoped>
    .content{
        .detail_mian{
            margin-top: 0;
            margin-bottom: 20px;
        }
    }
    .enterprise_info{
        height: 50px;
        line-height: 50px;
    }
    .posted-form-con {
        width: 90%;
        margin: 0 auto;
        padding: 12px 0 20px 0;
    }
    .posted-title-img {
        .el-form-item {
            margin-bottom: 0;
        }
        .posted-img-box {
            display: flex;
            justify-content: space-between;
            margin-left: 40px;
            margin-bottom: 40px;
            .img-box {
                width: 320px;
                height: 240px;
                border: 1px dashed $__color-border;
                box-sizing: border-box;
                display: flex;
                justify-content: center;
                align-items: center;
                position: relative;
                /*img {*/
                    /*max-width: 238px;*/
                    /*max-height: 154px;*/
                /*}*/
                .delete-bill-btn {
                    position: absolute;
                    top: 0;
                    right: 0;
                    cursor: pointer;
                }
                .icon-shangchuanshanchu {
                    color: $__color-remind;
                    font-size: 20px;
                }
            }
        }
    }
    .accept_bank{
        position: relative;
    }
    .discount_date{
        margin-right: 18px;
    }
    .bill_price{
        position: relative;
        .company{
            position: absolute;
            top: 2px;
            right: 12px;
            font-size: 14px;
            color: $__color-show;
        }
    }
    .searchResult{
        margin-left: 40px;
        height: 50px;
        line-height: 48px;
        border: 1px solid $__color-border;
        border-radius: 4px;
        .el-col{
            text-align: center;
            background-color: $__color-bg-primary;
            color: $__color-label;
            font-size: 14px;
            &:first-child{
                background-color: #fff;
                color: $__color-show;
            }
        }
    }
    .add_bill{
        height: 40px;
        background-color: $__color-bg-primary;
        line-height: 40px;
        .center{
            width: 70%;
            height: 100%;
            margin: 0 auto;
            .title{
                color: $__color-show;
                font-size: 14px;
                margin-right: 60px;
            }
            .add_btn{
                float: right;
                margin-top: 4px;
                width: 260px;
                border: 1px solid $__color-link !important;
                color: $__color-link !important;
                background: $__color-bg-multiple !important;
                &:hover{
                    border: 1px solid $__color-link;
                    color: $__color-link;
                    background: $__color-bg-multiple;
                }
            }
        }
    }
    .pubish{
        text-align: center;
        margin: 20px 0 40px 0;
        .el-button{
            width: 320px;
        }
    }
    .hr{
        height: 1px;
        background-color: $__color-line !important;
    }
    .publish_tips{
        width: 70%;
        margin: 0 auto;
        padding-top: 12px;
        div{
            float: left;
            font-size: 14px;
            color: $__color-label;
        }
        .secondary_title{
            font-size: 16px;
            color: $__color-show;
            font-weight: 600;
            width: 70px;
        }
        .secondary_content{
            width: calc(100% - 70px);
        }
    }
</style>
<style lang="scss">
    .picker_date{
        .el-date-editor.el-input, .el-date-editor.el-input__inner{
            width: 100% !important;
        }
    }
</style>